package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    /**
     * 进入controller之前执行此方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("*************拦截器开始了*************");
        //a.根据request对象获取请求头中token
        String headToken = request.getHeader("Authorization");
        //b.token如果为空直接返回401(用户没有访问权限，需要进行身份认证。)
        if (StringUtils.isEmpty(headToken)) {
            response.setStatus(401);
            return false;
        }
        //c.token如果不为空，根据token作为key到redis中获取用户对象
        User user = userService.getUserByToken(headToken);
        //d.如果用户对象为空，返回401
        if (StringUtils.isEmpty(user)) {
            response.setStatus(401);
            return false;
        }
        //e.如果用户对象不为空，通过UserHoler.setUser()存入ThreadLocal return true;
        UserHolder.setUser(user);
        log.debug("user{}*************拦截执行结束了*************",user.toString());
        return true;
    }
}
